package com.hdsx.netty.rpcserver.bio;

import com.hdsx.netty.monitor.BioMonitor;
import com.hdsx.netty.rpcserver.bio.handle.BusinessHandler;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 占贤银
 * time 2024/8/8 23:15
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class BioRegister {

    private int port;

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> registerMaps = new HashMap<>();

    // 定义一个线程池
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public BioRegister(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        BioRegister register = new BioRegister(8888);
        register.publish();
    }

    private void BioScannProvider() {
        doBioScan("com.hdsx.netty.rpcserver.bio.provider");
        doBioRegiter();
    }

    private void doBioRegiter() {
        try {
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if (aClass.isInterface()) {
                    return;
                }
                String interfaceName = aClass.getInterfaces()[0].getName();
                Object puaseObject = aClass.newInstance();
                BioMonitor bioMonitor = new BioMonitor(puaseObject);
                puaseObject = bioMonitor.create(aClass);
                if (!registerMaps.containsKey(interfaceName)) {
                    registerMaps.put(interfaceName, puaseObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doBioScan(String packageName) {
        URL url = this.getClass().getClassLoader()
                .getResource(packageName.replaceAll("\\.", "/"));
        File file = new File(url.getFile());
        for (File listFile : file.listFiles()) {
            String name = listFile.getName();
            if (listFile.isDirectory()) {
                // 如果是目录
                doBioScan(packageName + "." + name);
            } else if (listFile.isFile()) { // 如果是文件
                if (!name.endsWith(".class")) {
                    continue;
                }
                classNames.add(packageName + "." + name.replace(".class", ""));
            }
        }

    }

    // todo 由注册中心发布服务
    private void publish() {
        // todo 扫描provider包并且注册
        BioScannProvider();
        // todo 启动BIO服务端程序
        startup();
    }

    private void startup() {
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.setReceiveBufferSize(1024);
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(this.port));
            System.out.println("RPC服务端已发布，Listen at port: " + this.port);
            // todo 不断的轮询
            while (true) {
                // todo 等待客户端请求进来
                Socket socket = serverSocket.accept();
                System.out.println("连接 = " + socket.getRemoteSocketAddress());
                executorService.submit(new BusinessHandler(socket, registerMaps));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
